#    MythMobile, a Django interface to MythTV for mobile devices
#    Copyright (C) 2011 Andrew Wilkinson (andrewjwilkinson@gmail.com)
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License along
#     with this program; if not, write to the Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import json
import os
import SocketServer
import struct
import sys

import _mythmobile
import db_connection
from detect_encoder import detect_encoder
from msg_handlers import msg_handlers

import settings

int_size = struct.calcsize("i")

class RequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        remaining_data = ""

        while True:
            if len(remaining_data) >= int_size:
                data_size = remaining_data[:int_size]
                remaining_data = remaining_data[int_size:]
            else:
                data_size = ""
                while len(data_size) < int_size:
                    new_data = self.request.recv(4096)
                    if len(new_data) == 0:
                        return
                    data_size += new_data

                remaining_data += data_size[int_size:]
                data_size = data_size[:int_size]

            data_size = struct.unpack("i", data_size)[0]

            if len(remaining_data) >= data_size:
                data = remaining_data[:data_size]
                remaining_data = remaining_data[data_size:]
            else:
                data = ""
                while len(remaining_data) + len(data) < data_size:
                    new_data = self.request.recv(4096)
                    if len(new_data) == 0:
                        return
                    data += new_data

                remaining_data += data
                data = remaining_data[:data_size]
                remaining_data = remaining_data[data_size:]

            data = json.loads(data)

            r_msg = msg_handlers[data[0]](*data[1:])
            r_msg = json.dumps(r_msg)
            self.request.sendall(struct.pack("i", len(r_msg)) + r_msg)

class ThreadingUnixStreamServer(SocketServer.ThreadingMixIn, SocketServer.UnixStreamServer): pass

def main():
    print "MythMobile Daemon starting..."
    print "Copyright 2011 Andrew Wilkinson <andrewjwilkinson@gmail.com"
    print "MythMobile is released under the GNU GPL 2."

    try:
        os.remove(settings.BACKEND_SOCKET_PATH)
    except OSError:
        pass

    # Check that the directory has been created
    if not os.path.exists(settings.DATA_DIR):
        try:
            os.makedirs(settings.DATA_DIR)
        except OSError:
            sys.stderr.write("Failed to create %s.\n" % (settings.DATA_DIR, ))
            sys.exit(1)

    detect_encoder()

    db_connection.connect(*sys.argv[1:])
    
    server = SocketServer.ThreadingUnixStreamServer(settings.BACKEND_SOCKET_PATH, RequestHandler)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass

    print "MythMobile Daemon exiting..."
